<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>{{ roomInfo.name || '聊天房间' }}</h2>
      <button @click="leaveRoom" class="leave-btn">离开房间</button>
    </div>
    
    <div class="chat-messages">
      <div v-for="msg in messages" :key="msg.id" class="message-item">
        <div class="message-avatar">{{ msg.userAvatar }}</div>
        <div class="message-content">
          <div class="message-user">{{ msg.username }}</div>
          <div class="message-text">{{ msg.content }}</div>
          <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
        </div>
      </div>
    </div>
    
    <div class="chat-input">
      <textarea
        v-model="inputMessage"
        placeholder="输入消息..."
        @keyup.enter="sendMessage"
      ></textarea>
      <button @click="sendMessage" class="send-btn">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { roomApi } from '@/api'
import { useUserStore } from '@/stores/user'

uni.showToast({ title: '进入聊天页面', icon: 'none', duration: 1000 })
// 状态管理
const userStore = useUserStore()
const router = useRouter()

// 房间信息和消息
const roomId = ref(uni.getStorageSync('roomId') || '')
const roomInfo = ref({})
const messages = ref([])
const inputMessage = ref('')
let ws = null

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString()
}

// 获取房间信息
const getRoomInfo = async () => {
  try {
    const res = await roomApi.getRoomInfo(roomId.value)
    roomInfo.value = res.data
  } catch (error) {
    console.error('获取房间信息失败:', error)
    uni.showToast({ title: '获取房间信息失败', icon: 'none' })
  }
}

// 获取消息历史
const getMessageHistory = async () => {
  try {
    const res = await roomApi.getMessageHistory(roomId.value)
    messages.value = res.data
  } catch (error) {
    console.error('获取消息历史失败:', error)
    uni.showToast({ title: '获取消息历史失败', icon: 'none' })
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  try {
    const message = {
      roomId: roomId.value,
      content: inputMessage.value,
      userId: userStore.userId,
      username: userStore.userName,
      userAvatar: userStore.avatar || '默认头像'
    }

    // 先添加到本地显示
    messages.value.push({
      ...message,
      id: Date.now(),
      timestamp: new Date().getTime()
    })

    // 发送到服务器
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({
        type: 'chat_message',
        data: message
      }))
    } else {
      await roomApi.sendMessage(message)
    }

    inputMessage.value = ''
  } catch (error) {
    console.error('发送消息失败:', error)
    uni.showToast({ title: '发送消息失败', icon: 'none' })
  }
}

// 离开房间
const leaveRoom = async () => {
  try {
    await roomApi.leaveRoom(roomId.value)
    uni.navigateTo({ url: '/pages/room-list/room-list' })
  } catch (error) {
    console.error('离开房间失败:', error)
    uni.showToast({ title: '离开房间失败', icon: 'none' })
  }
}

// 初始化WebSocket连接
const initWebSocket = () => {
  // 实际项目中替换为真实的WebSocket地址
  const wsUrl = `ws://localhost:8080/ws/room/${roomId.value}?token=${userStore.token}`
  ws = new WebSocket(wsUrl)

  ws.onopen = () => {
    console.log('WebSocket连接已建立')
  }

  ws.onmessage = (event) => {
    const data = JSON.parse(event.data)
    if (data.type === 'chat_message') {
      messages.value.push(data.data)
    }
  }

  ws.onclose = () => {
    console.log('WebSocket连接已关闭')
  }

  ws.onerror = (error) => {
    console.error('WebSocket错误:', error)
  }
}

// 组件挂载时
onMounted(() => {
  if (!userStore.isLogin) {
    uni.navigateTo({ url: '/pages/login/login' })
    return
  }

  getRoomInfo()
  getMessageHistory()
  initWebSocket()
})

// 组件卸载时
onUnmounted(() => {
  if (ws) {
    ws.close()
  }
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.leave-btn {
  padding: 8px 16px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #ffffff;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
}

.message-content {
  flex: 1;
}

.message-user {
  font-weight: bold;
  margin-bottom: 4px;
}

.message-text {
  background-color: #f0f0f0;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  color: #888888;
}

.chat-input {
  display: flex;
  padding: 16px;
  border-top: 1px solid #e0e0e0;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  resize: none;
  height: 80px;
  margin-right: 12px;
}

.send-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  align-self: flex-end;
}
</style>